import re
from flask import Flask,request,make_response
from flask_cors import CORS
from werkzeug.wrappers import response
from database import db
import json

app = Flask(__name__)
CORS(app)
# 加载配置文件
from config import Config
app.config.from_object(Config)

@app.route('/',methods=['POST','GET'])
def userm():
    if request.method=='POST':
        data = json.loads(request.data)
        title = data['title']
        sql = "insert into news(title) values('%s')"%(title)
        db.insert(sql)
        return 'ok'
    else:
        userid = request.args.get('userid')
        return userid

# 钩子函数
@app.route('/text')
def text():
    return 'ok'
    
import time
@app.before_request
def before_quest():
    # 获取当前URL
    url = request.url
    # 获取当前时间戳
    nowtime = time.time()
    sql = "insert into visit(url,stime) values('%s',%d)"%(url,nowtime)
    db.insert(sql)
    print(url,nowtime)

@app.after_request
def after_request(response):
    # 获取当前URL
    url = request.url
    # 获取当前时间戳
    nowtime = time.time()
    #根据url去数据库中查询
    sql= "select * from visit where url='%s' and etime is Null"%(url)
    res = db.findone(sql)
    sql = "update visit set etime='%s' where id=%d"%(nowtime,res['id'])
    # sql = "insert into visit(stime,etime,url) values(%d,%d,'%s')"%(res['stime'],nowtime,url) 
    db.update(sql)
    # 结束更新时间
    return make_response(response)


# 运行
if __name__ == '__main__':
    app.run()
    